<template>
  <el-dialog :visible="visible" :title="title" @close="dialogClose">
    <!-- 表单区域 -->
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item label="权限名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="权限标识" prop="code">
        <el-input v-model="formData.code" />
      </el-form-item>
      <el-form-item label="权限描述" prop="description">
        <el-input v-model="formData.description" />
      </el-form-item>
      <el-form-item label="开启" prop="enVisible">
        <el-switch
          v-model="formData.enVisible"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-value="1"
          inactive-value="0"
        />
      </el-form-item>
    </el-form>
    <!-- 按钮区域 -->
    <template #footer>
      <div style="text-align: right">
        <el-button @click="dialogClose">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { addPermission, getPermissionDetail, updatePermission } from '@/api'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ''
    },
    pid: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 表单数据
      formData: {
        name: '',
        code: '',
        description: '',
        enVisible: ''
      },
      // 表单校验规则
      formRules: {
        name: [
          { required: true, message: '权限名称不能为空！', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空！', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.formData.id ? '编辑权限' : '新增权限'
    }
  },
  methods: {
    dialogClose() {
      this.$emit('close')
      // 关闭表单时，重置表单
      this.$refs.formRef.resetFields()
      this.formData = {
        name: '',
        code: '',
        description: '',
        enVisible: ''
      }
    },
    // 提交事件
    submit() {
      // 兜底校验
      this.$refs.formRef.validate(async(valid) => {
        if (!valid) return
        if (this.formData.id) {
          await updatePermission(this.formData)
        } else {
          await addPermission({ ...this.formData, type: this.type, pid: this.pid })
        }
        // 提示用户
        this.$message.success(this.title + '成功！')
        // 关闭弹窗
        this.dialogClose()
        // 通知父组件,更新数据
        this.$emit('update')
      })
    },
    // 获取权限限点详情
    async getDetail(id) {
      const { data } = await getPermissionDetail(id)
      this.formData = data
      console.log(data)
    }
  }
}
</script>

<style>
</style>
